package com.eshop.controller;

import com.eshop.api.ApiResult;
import com.eshop.common.condition.HttpPathCheckCondition;
import com.eshop.common.strategy.uploadImg.upLoadImg;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Conditional(HttpPathCheckCondition.class)
@RestController
@RequiredArgsConstructor
public class FileController {
//    private final upLoadImg upLoadImg;

    @GetMapping("/file/{path}/{fileName}")
    public void getImg(HttpServletRequest request, HttpServletResponse response,
                                     @PathVariable("path") String path,@PathVariable("fileName")String fileName){
//        upLoadImg.getImg(path,fileName,response);
        ServletOutputStream outputStream = null;
        InputStream decryptInputStream = getInputStream(path,fileName);
        try{
            response.reset();
            outputStream = response.getOutputStream();
            response.setHeader("Pragma","no-cache");
            response.setHeader("Cache-Control","no-cache");
            response.setDateHeader("Expires",0);
            //因为我的图片是png格式的，所以我在contentType写死了。实际开发中，根据图片类型来修改相应的contentType
            response.setContentType("image/png");
            // 在http响应中输出流
            byte[] cache = new byte[1024];
            int nRead = 0;
            while ((nRead = decryptInputStream.read(cache)) != -1) {
                outputStream.write(cache, 0, nRead);
                outputStream.flush();
            }
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //获取输入流
    public static InputStream getInputStream(String file,String fileName) {
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL("http://110.40.176.175:91/static/api/file/"+file+"/"+fileName);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(3000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                inputStream = httpURLConnection.getInputStream();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return inputStream;
    }

//    public static void main(String[] args) {
//        System.out.println("qwe/{file}/{fileName}");
//    }
}
